package com.lx.wx.controller;

import com.lx.bean.*;
import com.lx.mvc.ResponseBody;
import com.lx.service.CourierService;
import com.lx.service.ExpressService;
import com.lx.service.UserService;
import com.lx.util.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @ClassName: WXController
 * @Description:
 * @Date Created in  2021-07-17 15:11
 * @Modified By:
 * @Author: 零巽
 */
public class WXController {

    @ResponseBody("/wx/loginSMS.do")
    public String sendSMS(HttpServletRequest req, HttpServletResponse resp) {
        String userPhone = req.getParameter("userPhone");
        String code = RandomUtil.getCode() + "";
        System.out.println(code);
        boolean send = SMSUtil.send(userPhone, code);
        send = true;//短信功能未使用
        Message message = new Message();
        if (send) {
            message.setStatus(0);
            message.setResult("短信发送成功，请注意查收！");
        } else {
            message.setStatus(-1);
            message.setResult("短信发送失败，请检查手机号或稍后再试！");
        }
        UserUtil.setLoginSMS(req.getSession(), userPhone, code);
        return JsonUtil.toJSON(message);

    }

    @ResponseBody("/wx/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        String userPhone = req.getParameter("userPhone");
        HttpSession session = req.getSession();
        Message message = new Message();
        if (userPhone == null || userPhone.length() == 0) {
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie:cookies) {
                String cookieName = cookie.getName();
                if ("userPhone".equals(cookieName)) {
                    String phone = cookie.getValue();
                    if (phone != null) {
                        message.setStatus(0);
                        message.setResult("自动登录成功");
                        User user = new User();
                        user.setPhone(phone);
                        UserUtil.setUser(session, user);
                        Courier courier = CourierService.findByPhone(phone);
                        //实现自动登录
                        if (courier != null) {
                            //说明是快递员
                            session.setAttribute("role", "courier");
                            session.setAttribute("sysPhone", phone);
                        } else {
                            session.setAttribute("role", "user");
                        }
                    }
                    return JsonUtil.toJSON(message);
                }
            }
        }

        String code = req.getParameter("code");
        String autoLogin = req.getParameter("autoLogin");
        String sysCode = UserUtil.getLoginSMS(session, userPhone);
        if (code.equals(sysCode)) {
            message.setStatus(0);
            User user = new User();
            user.setPhone(userPhone);
            UserUtil.setUser(session, user);
            Courier courier = CourierService.findByPhone(userPhone);
            //实现自动登录
            if (courier != null) {
                //说明是快递员
                session.setAttribute("role", "courier");
                session.setAttribute("sysPhone", userPhone);
            } else {
                session.setAttribute("role", "user");
                User userFindByPhone = UserService.findByPhone(userPhone);
                if (userFindByPhone == null) {
                    //说明没注册过
                    UserService.addUser(user);
                }
            }
            //自动登录存储用户手机号
            if (Integer.parseInt(autoLogin) == 1) {
                Cookie cookie = new Cookie("userPhone", userPhone);
                cookie.setMaxAge(60 * 60);//一小时有效期
                cookie.setPath("/");//设置cookie的存储录路径，不然无法读取！！！
                resp.addCookie(cookie);
            }
        } else {
            message.setStatus(-1);
            message.setResult("验证码不一致！请检查后重试！");
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/logout.do")
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        req.getSession().invalidate();
        //退出时同步清除cookie
        Cookie cookie = new Cookie("userPhone", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");//同步cookie的路径以覆盖原cookie
        resp.addCookie(cookie);
        Message message = new Message();
        message.setResult("退出成功！");
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/role.do")
    public String role(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        String role = (String) session.getAttribute("role");
        Message message = new Message();
        if ("courier".equals(role)) {
            //说明是快递员
            message.setStatus(0);
        } else if ("user".equals(role)) {
            //说明是用户
            message.setStatus(1);
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/getExpressByUserPhone.do")
    public String getExpressByUserPhone(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        String phone = user.getPhone();
        List<Express> list = ExpressService.findByUserPhone(phone);
        List<BootstrapTableExpress> expressList = new ArrayList<>();
        for (Express e : list) {
            String inTime = DateFormatUtil.format(e.getInTime());
            String outTime = e.getOutTime() == null ? "未出库" : DateFormatUtil.format(e.getOutTime());
            String status = e.getStatus() == 0 ? "未取件" : "已取件";
            String code = e.getCode() == null || e.getCode().length() == 0 ? "已取件" : e.getCode();
            BootstrapTableExpress express = new BootstrapTableExpress(e.getId(), e.getNumber(), e.getUserName(), e.getUserPhone(), e.getCompany(), code, inTime, outTime, status, e.getSysPhone());
            expressList.add(express);
        }
        //用listFilter筛选数据
        Object[] data0 = expressList.stream().filter(e -> {
            if (e.getStatus() == "未取件") {
                return true;
            } else {
                return false;
            }
        }).sorted((o1, o2) -> {
            return (int) (DateFormatUtil.toTime(o1.getInTime()) - DateFormatUtil.toTime(o2.getInTime()));
        }).toArray();
        Object[] data1 = expressList.stream().filter(e -> {
            if (e.getStatus() == "已取件") {
                return true;
            } else {
                return false;
            }
        }).sorted((o1, o2) -> {
            return (int) (DateFormatUtil.toTime(o1.getInTime()) - DateFormatUtil.toTime(o2.getInTime()));
        }).toArray();
        Map data = new HashMap();
        data.put("status0", data0);
        data.put("status1", data1);
        Message message = new Message();
        if (expressList == null) {
            message.setStatus(-1);
            message.setResult("查询失败，暂无快递！");
        } else {
            message.setStatus(0);
            message.setData(data);
            message.setResult("查询成功！");
        }
        return JsonUtil.toJSON(message);

    }

    @ResponseBody("/wx/getExpress.do")
    public String getExpress(HttpServletRequest req, HttpServletResponse resp) {
        String userPhone = req.getParameter("userPhone");
        List<Express> expressList = ExpressService.findByUserPhone(userPhone);
        List<BootstrapTableExpress> expressList2 = new ArrayList<>();
        for (Express e : expressList) {
            String inTime = DateFormatUtil.format(e.getInTime());
            String outTime = e.getOutTime() == null ? "未出库" : DateFormatUtil.format(e.getOutTime());
            String status = e.getStatus() == 0 ? "未取件" : "已取件";
            String code = e.getCode() == null || e.getCode().length() == 0 ? "已取件" : e.getCode();
            BootstrapTableExpress express = new BootstrapTableExpress(e.getId(), e.getNumber(), e.getUserName(), e.getUserPhone(), e.getCompany(), code, inTime, outTime, status, e.getSysPhone());
            expressList2.add(express);
        }
        for (int i = 0; i < expressList2.size(); i++) {
            System.out.println("expressList" + expressList2.get(i));
        }
        Object[] objects = expressList2.stream().filter(express -> {
            if ("未取件".equals(express.getStatus())) {
                return true;
            } else {
                return false;
            }
        }).toArray();
        System.out.println("object" + objects);
        Message message = new Message();
        if (objects == null || objects.length == 0) {
            message.setStatus(-1);
            message.setResult("暂无快递！");
        } else {
            message.setStatus(0);
            message.setData(objects);
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/findExpressByNumber.do")
    public String findExpressByNumber(HttpServletRequest req, HttpServletResponse resp) {
        String number = req.getParameter("number");
        Express e = ExpressService.findByNumber(number);
        Message message = new Message();
        if (e == null) {
            message.setStatus(-1);
            message.setResult("未查询到快递！请检查单号！");
        } else {
            String inTime = DateFormatUtil.format(e.getInTime());
            String outTime = e.getOutTime() == null ? "未出库" : DateFormatUtil.format(e.getOutTime());
            String status = e.getStatus() == 0 ? "未取件" : "已取件";
            String code = e.getCode() == null || e.getCode().length() == 0 ? "已取件" : e.getCode();
            BootstrapTableExpress express = new BootstrapTableExpress(e.getId(), e.getNumber(), e.getUserName(), e.getUserPhone(), e.getCompany(), code, inTime, outTime, status, e.getSysPhone());
            message.setStatus(0);
            message.setData(express);
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/addExpress.do")
    public String addExpress(HttpServletRequest req, HttpServletResponse resp) {
        String number = req.getParameter("number");
        String userName = req.getParameter("userName");
        String userPhone = req.getParameter("userPhone");
        String company = req.getParameter("company");
        String sysPhone = UserUtil.getSysPhone(req.getSession());
        Express express = new Express(number, userName, userPhone, company, sysPhone);
        boolean add = ExpressService.add(express);
        //添加快递查询是否存在该用户，如果不存在则同步根据手机号添加一个只存储姓名和电话的用户，否则会在调取排行榜时出错
        User byPhone = UserService.findByPhone(userPhone);
        if (byPhone == null) {
            User user = new User();
            user.setPhone(userPhone);
            user.setUserName(userName);
            UserService.addUser(user);
        }
        Message message = new Message();
        if (add) {
            message.setStatus(0);
            message.setResult("添加成功！");
        } else {
            message.setStatus(-1);
            message.setResult("添加失败,单号已存在！");
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/checkData.do")
    public String checkData(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        User user = UserUtil.getUser(session);
        String phone = user.getPhone();
        User getUser = UserService.findByPhone(phone);
        Message message = new Message();
        if (getUser.getUserName() != null && getUser.getPassword() != null) {
            //说明有用户信息
            message.setStatus(1);
            message.setData(getUser);
        } else {
            message.setStatus(0);
            message.setData(user);
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/getHistoryExpressByUserPhone.do")
    public String getHistoryExpressByUserPhone(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        String phone = user.getPhone();
        List<Express> list = ExpressService.findBySysPhone(phone);
        List<BootstrapTableExpress> expressList = new ArrayList<>();
        for (Express e : list) {
            String inTime = DateFormatUtil.format(e.getInTime());
            String outTime = e.getOutTime() == null ? "未出库" : DateFormatUtil.format(e.getOutTime());
            String status = e.getStatus() == 0 ? "未取件" : "已取件";
            String code = e.getCode() == null || e.getCode().length() == 0 ? "已取件" : e.getCode();
            BootstrapTableExpress express = new BootstrapTableExpress(e.getId(), e.getNumber(), e.getUserName(), e.getUserPhone(), e.getCompany(), code, inTime, outTime, status, e.getSysPhone());
            expressList.add(express);
        }
        //用listFilter筛选数据
        Object[] historyExpressList = expressList.stream().filter(e -> {
            if (e.getStatus() == "已取件") {
                return true;
            } else {
                return false;
            }
        }).sorted((o1, o2) -> {
            return (int) (DateFormatUtil.toTime(o1.getInTime()) - DateFormatUtil.toTime(o2.getInTime()));
        }).toArray();
        Message message = new Message();
        if (historyExpressList == null) {
            message.setStatus(-1);
            message.setResult("查询失败，暂无历史快递！");
        } else {
            message.setStatus(0);
            message.setData(historyExpressList);
            message.setResult("查询成功！");
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/updateStatus.do")
    public String updateStatusByCode(HttpServletRequest req, HttpServletResponse resp) {
        String code = req.getParameter("code");
        boolean b = ExpressService.changeStatusByCode(code);
        Message message = new Message();
        if (b) {
            message.setStatus(0);
            message.setResult("取件成功！");
        } else {
            message.setStatus(-1);
            message.setResult("取件失败，请重试！");
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/findExpressByCode.do")
    public String findExpressByCode(HttpServletRequest req, HttpServletResponse resp) {
        String code = req.getParameter("code");
        Express e = ExpressService.findByCode(code);
        Message message = new Message();
        if (e == null) {
            message.setStatus(-1);
            message.setResult("未查询到快递，请输入正确的取件码！");
        } else {
            String inTime = DateFormatUtil.format(e.getInTime());
            String outTime = e.getOutTime() == null ? "未出库" : DateFormatUtil.format(e.getOutTime());
            String status = e.getStatus() == 0 ? "未取件" : "已取件";
            String getCode = e.getCode() == null || e.getCode().length() == 0 ? "已取件" : e.getCode();
            BootstrapTableExpress express = new BootstrapTableExpress(e.getId(), e.getNumber(), e.getUserName(), e.getUserPhone(), e.getCompany(), getCode, inTime, outTime, status, e.getSysPhone());
            message.setStatus(0);
            message.setData(express);
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/getCode.do")
    public String getCode(HttpServletRequest req, HttpServletResponse resp) {
        String phone = req.getParameter("phone");
        String code = RandomUtil.getCode() + "";
        boolean send = SMSUtil.send(phone, code);
        send = true;//未设置发送短信功能，默认成功
        System.out.println(code);
        Message message = new Message();
        if (send) {
            message.setStatus(0);
            message.setResult("短信发送成功，请注意查收!");
            message.setData(code);
        } else {
            message.setStatus(-1);
            message.setResult("短信发送失败，请稍后再试");
        }

        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/updateUserInfo.do")
    public String updateUserInfo(HttpServletRequest req, HttpServletResponse resp) {
        String userName = req.getParameter("userName");
        String userPhone = req.getParameter("userPhone");
        String password = req.getParameter("password");
        String oldPhone = req.getParameter("oldPhone");
        User oldUser = UserService.findByPhone(oldPhone);
        int id = oldUser.getId();
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setPhone(userPhone);
        boolean b = UserService.updateWXUser(id, user);
        Message message = new Message();
        if (b) {
            message.setStatus(0);
            message.setResult("设置信息成功！");
        } else {
            message.setStatus(-1);
            message.setResult("信息设置失败，请重试！");
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/getUserName.do")
    public String getUserName(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        User user = UserUtil.getUser(session);
        String phone = user.getPhone();
        User findUser = UserService.findByPhone(phone);
        String userName = findUser.getUserName();
        Message message = new Message();
        if (userName == null) {
            message.setStatus(-1);
        } else {
            message.setStatus(0);
            message.setData(findUser);
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/updateUserNameAndPhone.do")
    public String updateUserNameAndPhone(HttpServletRequest req, HttpServletResponse resp) {
        String userName = req.getParameter("userName");
        String newPhone = req.getParameter("newPhone");
        String oldPhone = req.getParameter("oldPhone");
        User user = new User();
        user.setPhone(newPhone);
        user.setUserName(userName);
        User byPhone = UserService.findByPhone(oldPhone);
        int id = byPhone.getId();
        boolean b = UserService.updateUserNameAndPhone(id, user);
        Message message = new Message();
        if (b) {
            message.setStatus(0);
            message.setResult("数据更新成功！");
        } else {
            //同步更新session
            HttpSession session = req.getSession();
            UserUtil.setUser(session, user);
            message.setStatus(-1);
            message.setResult("数据更新失败，请重试！");
        }
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/wx/getLazyBoard.do")
    public String getLazyBoard(HttpServletRequest req, HttpServletResponse resp) {
        List[] monthLazyBoard = ExpressService.getMonthLazyBoard();
        List[] totalLazyBoard = ExpressService.getTotalLazyBoard();
        List[] yearLazyBoard = ExpressService.getYearLazyBoard();
        List data = new ArrayList();
        data.add(totalLazyBoard);
        data.add(yearLazyBoard);
        data.add(monthLazyBoard);
        Message message = new Message();
        message.setData(data);
        return JsonUtil.toJSON(message);


    }
}
